// pages/home/particulars/index.js
import { home } from "../../../api/index";
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navObjWid: app.globalData.navObjWid,
    IMGBASEURL: app.globalData.IMGBASEURL,
    topDistance: "",
    bottomDistance: "",
    id: "",
    imgUrl: "",
    particularsData: {},
    swiperList: [],
    params: {},
    describe: "",
    lableList: [],
    current: 1, //轮播图当前页数
    rectRight: 0,
    navTop: "",
    navHeight: 0,
    isFollow: false,
    pageType: "",
    winWidth: 0,
    imgHight: "",
    //评论数据
    PageIndex: 1,
    PageSize: 10,
    ID: "",
    loading: false, //是否正在加载数据
    commentList: [],
    TotalCount: 1,
    RouterUserId: "", //路由传递过来的用户id
  },
  onClick(even) {
    console.log(even.currentTarget.dataset.url);
    wx.previewImage({
      current: even.currentTarget.dataset.url, // 当前显示图片的http链接
      urls: this.data.params.Pictures, // 需要预览的图片http链接列表
    });
  },

  //返回上一级
  goBack() {
    if (this.data.pageType === "share") {
      wx.switchTab({
        url: "/pages/home/index",
      });
    } else {
      wx.navigateBack();
    }
  },
  // 改变swiper页码
  swiperChange(e) {
    const current = e.detail.current + 1; // 因为索引是从0开始的，所以需要加1
    this.setData({
      current,
    });
  },
  // 获取数据
  async getData() {
    let res = await home.getDetail({
      ID: this.data.id,
    });
    res.Result.MainContent=decodeURI( res.Result.MainContent)
    this.setData({
      params: res.Result,
      describe: decodeURIComponent(res.Result.MainContent),
    });
    const _this = this;
    wx.getImageInfo({
      src: this.data.params.Pictures[0],
      success: (res) => {
        //设置图片宽高比
        let num = res.width / res.height;
        _this.setData({
          imgHight: (_this.data.winWidth / num) * 2 + "rpx",
        });
      },
    });
    this.checkFollow();
    this.getCommentData();
  },
  // 点赞/取消点赞
  Ilike() {
    const _this = this;
    const obj = {
      LikeID: this.data.params.ID,
    };
    home[
      this.data.params.IsLike ? "removelikeformcontent" : "addlikeformcontent"
    ](obj)
      .then((res) => {
        console.log(res, "res");
        if (res.StatusCode === 200) {
          const num = this.data.params.IsLike
            ? (this.data.params.LikeCount -= 1)
            : (this.data.params.LikeCount += 1);
          this.setData({
            "params.IsLike": !this.data.params.IsLike,
            "params.LikeCount": num,
          });
        }
      })
      .catch((err) => {
        if (err.statusCode === 401) {
          _this.shudLogin();
        } else {
          wx.showToast({
            title: "请稍后重试！",
            icon: "error",
          });
        }
      });
  },
  // 收藏、取消收藏
  Icollection() {
    const _this = this;
    const obj = {
      ContentID: this.data.params.ID,
    };
    home[
      this.data.params.IsCollect
        ? "removecollectionformcontent"
        : "addcollectionformcontent"
    ](obj)
      .then((res) => {
        if (res.StatusCode === 200) {
          const num = this.data.params.IsCollect
            ? (this.data.params.CollectCount -= 1)
            : (this.data.params.CollectCount += 1);
          this.setData({
            "params.IsCollect": !this.data.params.IsCollect,
            "params.CollectCount": num,
          });
        }
      })
      .catch((err) => {
        if (err.statusCode === 401) {
          _this.shudLogin();
        }
      });
  },
  // 去评论详情
  toCommentDetail() {
    wx.navigateTo({
      url: "/pages/home/commentDetail/index?ID=" + this.data.params.ID,
    });
  },
  //判断是否关注
  async checkFollow() {
    // 登录了才调用
    let _this = this;
    let token = wx.getStorageSync("token");
    if (token) {
      let res = await home.isfollowtouser({
        ID: _this.data.params.CreateUserId,
      });
      this.setData({
        isFollow: res.Result,
      });
    }
  },
  //关注
  async Ifollow() {
    const _this = this;
    home[this.data.isFollow ? "removefollow" : "addfollow"]({
      ID: this.data.params.CreateUserId,
    })
      .then((res) => {
        if (res.StatusCode === 200) {
          this.setData({
            isFollow: !_this.data.isFollow,
          });
          wx.showToast({
            title: _this.data.isFollow ? "关注成功" : "取关成功",
            mask: "true",
          });
        }
      })
      .catch((err) => {
        if (err.statusCode === 401) {
          _this.shudLogin();
        }
      });
  },
  //去登录
  shudLogin() {
    const popup = this.selectComponent("#popupid");
    console.log("popup", popup);
    popup.setData({
      visible: true,
      isNavBar: false,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    const _this = this;
    let data = JSON.parse(decodeURIComponent(options.data));

    wx.getSystemInfo({
      success: (res) => {
        let systemInfo = wx.getSystemInfoSync();
        let info = wx.getMenuButtonBoundingClientRect();
        _this.setData({
          navTop: res.statusBarHeight,
          navHeight: (info.top - systemInfo.statusBarHeight) * 2 + info.height,
          winWidth: res.windowWidth,
        });
      },
      fail(err) {
        console.log(err);
      },
    });
    this.setData({
      topDistance: app.globalData.navHeightM + "rpx",
      topDistance_2: app.globalData.navHeightM * 2 + "rpx",
      bottomDistance: app.globalData.bottomSafeDistance + "rpx",
      id: data.ID,
      pageType: data.pageType,
      RouterUserId: data.UserId,
    });
    this.getData();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // let countDown = this.selectComponent('#countDown');
    // countDown.getData();
    this.getCommentData();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const _this = this;
    const obj = JSON.stringify({
      ID: _this.data.id,
      pageType: "share",
    });
    return {
      title: _this.data.params.Title,
      path: `/pages/home/particulars/index?data=${obj}`,
    };
  },

  //评论数据
  async getCommentData() {
    // 如果正在加载数据，则直接返回，避免重复加载
    if (this.data.loading) {
      return;
    }
    // 设置加载中的标志
    this.setData({
      loading: true,
    });
    if (this.data.commentList.length === this.data.TotalCount) {
      return;
    }
    const { PageIndex, PageSize } = this.data;
    let res = await home.commentsortbyhot({
      PageIndex,
      PageSize,
      ID: this.data.params.ID,
    });
    res.Result.Datas.forEach((item) => {
      // 设置每个一级评论下的二级评论数据的初始状态
      item.showSecondary = false;
      item.secondaryCommentList = [];
    });
    this.setData({
      commentList: this.data.commentList.concat(res.Result.Datas),
      TotalCount: res.Result.TotalCount,
      PageIndex: this.data.PageIndex + 1,
      loading: false,
    });
  },
  /**
   * 去他人主页
   */
  toOthersPage() {
    wx.navigateTo({
      url: `/pages/my/othersPage/index?code=${this.data.params.UserCode}`,
    });
    // const token = wx.getStorageSync("token");
    // if (token) {
      
    // } else {
    //   this.shudLogin();
    // }
  },
});
